const { src, dest, series, parallel, watch} = require('gulp')
const bs = require('browser-sync').create()
const plugins = require('gulp-load-plugins')();
const del = require('del')

const data = {}

const clean = () => {
    return del(['dist'])
}

const cssTask = () => {
    return src('src/assets/styles/*.scss', { base: 'src'})
    .pipe(plugins.sass())
    .pipe(dest('temp'))
}

const jsTask = () => {
    return src('src/assets/scripts/*.js', { base: 'src'})
    .pipe(plugins.babel({presets: ['@babel/preset-env']}))
    .pipe(dest('temp'))
}

const htmlTask = () => {
    return src('src/*.html', { base: 'src'})
    .pipe(plugins.swig())
    .pipe(dest('temp'))
}

const imageTask = () => {
    return src('src/assets/images/**', { base: 'src'})
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const fontTask = () => {
    return src('src/assets/fonts/**', { base: 'src'})
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const extra = () => {
    return src('public/**', { base: 'public'})
    .pipe(dest('dist'))
}

const useref = () => {
    return src('temp/*.html', { base: 'temp'})
    .pipe(plugins.useref({ searchPath: ['temp', '.']}))
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
        collapseWhitespace: true,
        minifyCSS: true,
        minifyJS: true
    })))
    .pipe(dest('dist'))
}

const compile = parallel(cssTask, jsTask, htmlTask)

const serve = () => {
    watch('src/assets/styles/*.scss', cssTask)
    watch('src/assets/scripts/*.js', jsTask)
    watch('src/*.html', htmlTask)
    // 对于静态资源的监听
    watch([
        'src/assets/images/*',
        'src/assets/fonts/*',
        'public/**'
    ], bs.reload)

    bs.init({
        notify: false,
        files: 'temp/**',
        server: {
            baseDir: ['temp', 'src', 'public'],
            routes: {
                '/node_modules': 'node_modules'
            }
        }
    })
}

const build = series(clean, series(compile, useref), imageTask, fontTask, extra)

const dev = series(compile, serve)

module.exports = {
    // cssTask,
    // jsTask,
    // htmlTask,
    // imageTask,
    // fontTask,
    clean,
    // extra,
    // useref,
    // serve,
    // compile,
    build,
    dev
}